<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * @author Anh Nguyen <duyanhnguyen@vccorp.vn>
 * @copyright 2012
 */
class Commercial extends MX_Controller
{

    function __construct()
    {
        parent::__construct();
        $this->load->library('Admin_Layout');
        $this->load->model('commercial/commercial_model');
        $this->load->library('pagination');
        $this->load->helper('url');
        $this->load->library('table');
    }

    public function add()
    {
        $this->mycommon->authAdmin();
        $data = array();
        $data['error'] = '';
        $this->load->library('Form_validation');
        $this->load->library('Minifier');
        $this->minifier->AddJsNoPack('jquery.meio.mask');
        $this->form_validation->CI = & $this;
        $data['current'] = 16;
        $this->form_validation->set_error_delimiters('<li>', '</li>');
        if ($this->input->post('submit') && $this->input->post('frmToken') && $this->session->userdata('frmToken') && $this->input->post('frmToken') == $this->session->userdata('frmToken')) {
            $this->form_validation->set_rules('name', 'Tên quảng cáo', 'required|min_length[3]');
            $this->form_validation->set_rules('upload', 'File quảng cáo', 'required');
            $this->form_validation->set_rules('url', 'Địa chỉ liên kết', 'required|min_length[3]');
            $this->form_validation->set_rules('width', 'Độ rộng', 'required|min_length[1]');
            $this->form_validation->set_rules('height', 'Độ cao', 'required|min_length[1]');
            $this->form_validation->set_message('required', '%s không được để trống');
            $this->form_validation->set_message('min_length', '%s ít nhất %d ký tự');
            if ($this->form_validation->run() == TRUE) {
                $name = $this->input->post('name', TRUE);
                $upload = $this->input->post('upload', TRUE);
                $width = $this->input->post('width', TRUE);
                $Width = intval($width);
                $Width = ($Width > 174) ? 174 : $Width;
                $height = $this->input->post('height', TRUE);
                $Height = intval($height);
                $href = $this->input->post('url', TRUE);
                $location = $this->input->post('location', TRUE);
                $no= $this->input->post('no', TRUE);
                $Location = ($location == 1) ? 1 : 2;
                $No = intval($no);
                if ($name != '') {
                    if ($this->commercial_model->addCommercial($name, $upload, $Width, $Height, $href, $Location, $No)) {
                        redirect('admin/commercial');
                    }
                } else {
                    $data['error'] = 'Thông tin nhập vào chưa chính xác';
                }
            }
        }
        $data['frmToken'] = uniqid();
        $data['headTitle'] = 'Thêm quảng cáo';
        $this->session->set_userdata('frmToken', $data['frmToken']);
        $this->admin_layout->render('commercial/add_commercial_view', $data);
    }

    public function checkUrl($url)
    {
        if ($this->mycommon->isUrl($url)) {
            return true;
        }
        return false;
    }

    public function index($page = '')
    {
        $this->mycommon->authAdmin();
        $data = array();
        $page = ($page != '') ? intval($page) : 1;
        $keyword = $this->input->get('k');
        $numPost = $this->commercial_model->count_all($keyword);
        $config['base_url'] = '/admin/commercial/index';
        $config['total_rows'] = $numPost;
        $config['per_page'] = 10;
        $config['use_page_numbers'] = TRUE;
        $config['first_link'] = '«';
        $config['last_link'] = '»';
        $config['cur_tag_open'] = '<a href="#" class="active">';
        $config['cur_tag_close'] = '</a>';
        $config['num_links'] = '6';
        $config['cur_page'] = $page;
        $config['uri_segment'] = 3;
        $config["suffix"] = ".html?k=.$keyword";
        $this->pagination->initialize($config);
        $start = ($page - 1) * $config['per_page'];
        $data['pagination'] = $this->pagination->create_links();
        $data['headTitle'] = 'Quản lý quảng cáo';
        $data['current'] = 16;
        $data['keyword'] = $keyword;
        $this->load->library('Minifier');
        $data['advertising'] = $this->commercial_model->getAllAdvertising($config['per_page'],$start,$keyword);
        $this->admin_layout->render('commercial/commercial_view', $data);
    }

    public function hide($Id = '')
    {
        $this->mycommon->authAdmin();
        if ($Id == '') {
            show_404();
        }
        $data = array(
            'status' => '0'
        );
        $this->commercial_model->updateCommercialDeleteF($Id, $data);
        redirect('admin/commercial');
    }
    
    public function show($Id = '')
    {
        $this->mycommon->authAdmin();
        if ($Id == '' && intval($Id) != 0) {
            show_404();
        }
        $Id = intval($Id);
        $data = array(
            'status' => '1'
        );
        $this->commercial_model->updateCommercialDeleteF($Id, $data);
        redirect('admin/commercial');
    }

    public function delete($Id = '')
    {
        $this->mycommon->authAdmin();
        if ($Id == '' && intval($Id) != 0) {
            show_404();
        }
        $Id = intval($Id);
        $this->commercial_model->deleteCommercial($Id);
        redirect('admin/commercial');
    }

    public function edit($Id = '')
    {
        $this->mycommon->authAdmin();
        if ($Id == '' && intval($Id) != 0) {
            show_404();
        }
        $Id = intval($Id);
        $data = array();
        $data['error'] = '';
        $this->load->library('Form_validation');
        $this->load->library('Minifier');
        $this->minifier->AddJsNoPack('jquery.meio.mask');
        $this->form_validation->CI = & $this;
        $this->form_validation->set_error_delimiters('<li>', '</li>');
        $data['all'] = $this->commercial_model->getAdInfo($Id);
        if(!isset($data['all'][0]) && count($data['all'][0]) == 0)
            show_404 ();
        $data['current'] = 16;
        if ($this->input->post('submit') && $this->input->post('frmToken') && $this->session->userdata('frmToken') && $this->input->post('frmToken') == $this->session->userdata('frmToken')) {
            $this->form_validation->set_rules('name', 'Tên quảng cáo', 'required|min_length[3]');
            $this->form_validation->set_rules('upload', 'File quảng cáo', 'required');
            $this->form_validation->set_rules('url', 'Địa chỉ liên kết', 'required|min_length[3]');
            $this->form_validation->set_rules('width', 'Độ rộng', 'required|min_length[1]');
            $this->form_validation->set_rules('height', 'Độ cao', 'required|min_length[1]');
            $this->form_validation->set_message('required', '%s không được để trống');
            $this->form_validation->set_message('min_length', '%s ít nhất %d ký tự');
            if ($this->form_validation->run() == TRUE) {
                $name = $this->input->post('name', TRUE);
                $upload = $this->input->post('upload', TRUE);
                $width = $this->input->post('width', TRUE);
                $Width = intval($width);
                $Width = ($Width > 174) ? 174 : $Width;
                $height = $this->input->post('height', TRUE);
                $Height = intval($height);
                $href = $this->input->post('url', TRUE);
                $location = $this->input->post('location', TRUE);
                $no= $this->input->post('no', TRUE);
                $Location = ($location == 1)? 1 : 2;
                $No = intval($no);
                $array = array(
                    'name' => $name,
                    'img' => $upload,
                    'width' => $Width,
                    'height' => $Height,
                    'href' => $href,
                    'position' => $Location,
                    'order' => $No,
                    'status' => '1'
                );
                if ($name != '') {
                    if ($this->commercial_model->updateCommercial($Id,$array)) {
                        $this->mycommon->resetCache(APPPATH . 'cache');
                        redirect('admin/commercial');
                    }
                } else {
                    $data['error'] = 'Thông tin nhập vào chưa chính xác';
                }
            }
        }
        $data['frmToken'] = uniqid();
        $data['headTitle'] = 'Sửa thông tin quảng cáo';
        $this->session->set_userdata('frmToken', $data['frmToken']);
        $this->admin_layout->render('commercial/edit_commercial_view', $data);
    }
    
    public function upload()
    {
        $targetFolder = '/uploads/files';
        $res = array();
        $res['error'] = '';

        if (!empty($_FILES)) {
            $tempFile = $_FILES['Filedata']['tmp_name'];
            $fileName = $_FILES['Filedata']['name'];
            $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
            $fileName = explode('.', $fileName);
            $fileName[0] = $fileName[0] . '_' .  uniqid();
            $fileName = implode('.', $fileName);
            // Validate the file type
            $fileTypes = array('xls','xlsx'); // File extensions
            $targetFile = rtrim($targetPath,'/') . '/' . $fileName;
            $fileParts = pathinfo($_FILES['Filedata']['name']);
            if (in_array($fileParts['extension'],$fileTypes)) {
                move_uploaded_file($tempFile,$targetFile);
                $res['filename'] = $fileName;
            } else {
                $res['error'] = "File upload không hợp lệ";
            }
        } else {
            $res['error'] = 'Có lỗi xảy ra, vui lòng thực hiện lại';
        }
        echo json_encode($res);
    }
    
   
}

?>
